<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #333;
            text-align: center;
        }
        .upload-area {
            border: 2px dashed #ccc;
            padding: 40px 20px;
            text-align: center;
            margin-bottom: 30px;
            border-radius: 8px;
            transition: border-color 0.3s;
        }
        .upload-area:hover {
            border-color: #666;
        }
        #fileInput {
            display: none;
        }
        .upload-btn {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-bottom: 10px;
        }
        .upload-btn:hover {
            background-color: #45a049;
        }
        .file-info {
            color: #666;
            margin-bottom: 15px;
        }
        .upload-config {
            font-size: 14px;
            color: #888;
        }
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        .image-item {
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            position: relative;
        }
        .image-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }
        .image-info {
            padding: 10px;
            background-color: #f9f9f9;
        }
        .image-name {
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .image-size {
            font-size: 12px;
            color: #666;
        }
        .delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(255,0,0,0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .delete-btn:hover {
            background-color: rgba(255,0,0,1);
        }
        .status-message {
            padding: 10px;
            margin: 15px 0;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            display: block;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
            display: block;
        }
        .loading {
            text-align: center;
            padding: 20px;
            display: none;
        }
        .loading.show {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>图片管理系统</h1>
        
        <div class="status-message" id="statusMessage"></div>
        
        <div class="upload-area">
            <button class="upload-btn" id="selectFilesBtn">选择图片</button>
            <input type="file" id="fileInput" accept="image/*" multiple>
            <div class="file-info" id="fileInfo">未选择任何文件</div>
            <button class="upload-btn" id="uploadBtn">上传图片</button>
            <div class="upload-config">
                支持格式: JPG, PNG, GIF | 最大文件大小: 5MB | 最多同时上传: 5个文件
            </div>
        </div>
        
        <div class="loading" id="loading">上传中，请稍候...</div>
        
        <h2>已上传图片</h2>
        <div class="image-grid" id="imageGrid">
            <!-- 图片将通过JavaScript动态加载 -->
        </div>
    </div>

    <script>
        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const selectFilesBtn = document.getElementById('selectFilesBtn');
        const fileInfo = document.getElementById('fileInfo');
        const uploadBtn = document.getElementById('uploadBtn');
        const statusMessage = document.getElementById('statusMessage');
        const imageGrid = document.getElementById('imageGrid');
        const loading = document.getElementById('loading');
        
        // 选择文件按钮点击事件
        selectFilesBtn.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 文件选择变化事件
        fileInput.addEventListener('change', (e) => {
            const files = e.target.files;
            if (files.length > 0) {
                fileInfo.textContent = `已选择 ${files.length} 个文件`;
            } else {
                fileInfo.textContent = '未选择任何文件';
            }
        });
        
        // 上传按钮点击事件
        uploadBtn.addEventListener('click', async () => {
            const files = fileInput.files;
            if (files.length === 0) {
                showMessage('请先选择文件', 'error');
                return;
            }
            
            // 检查文件数量
            if (files.length > 5) {
                showMessage('最多只能上传5个文件', 'error');
                return;
            }
            
            // 检查文件类型和大小
            for (const file of files) {
                const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                if (!allowedTypes.includes(file.type)) {
                    showMessage(`文件 ${file.name} 类型不支持，仅支持JPG、PNG、GIF`, 'error');
                    return;
                }
                
                if (file.size > 5 * 1024 * 1024) {
                    showMessage(`文件 ${file.name} 过大，最大支持5MB`, 'error');
                    return;
                }
            }
            
            // 创建FormData并添加文件
            const formData = new FormData();
            for (const file of files) {
                formData.append('images', file);
            }
            
            try {
                // 显示加载状态
                loading.classList.add('show');
                showMessage('', '');
                
                // 发送上传请求
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                // 隐藏加载状态
                loading.classList.remove('show');
                
                if (result.success) {
                    showMessage(result.message, 'success');
                    // 清空选择的文件
                    fileInput.value = '';
                    fileInfo.textContent = '未选择任何文件';
                    // 重新加载图片列表
                    loadImageList();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                loading.classList.remove('show');
                showMessage('上传失败: ' + error.message, 'error');
            }
        });
        
        // 加载图片列表
        async function loadImageList() {
            try {
                const response = await fetch('/list');
                const images = await response.json();
                
                imageGrid.innerHTML = '';
                
                if (images.length === 0) {
                    imageGrid.innerHTML = '<p>暂无上传的图片</p>';
                    return;
                }
                
                // 渲染图片列表
                images.forEach(image => {
                    const imageItem = document.createElement('div');
                    imageItem.className = 'image-item';
                    
                    // 格式化文件大小
                    const fileSize = (image.size / 1024).toFixed(1) + ' KB';
                    
                    imageItem.innerHTML = `
                        <img src="/files/${image.filename}" alt="${image.originalname}">
                        <div class="image-info">
                            <div class="image-name">${image.originalname}</div>
                            <div class="image-size">${fileSize}</div>
                        </div>
                        <button class="delete-btn" data-id="${image.id}" data-filename="${image.filename}">×</button>
                    `;
                    
                    imageGrid.appendChild(imageItem);
                });
                
                // 为删除按钮添加事件
                document.querySelectorAll('.delete-btn').forEach(btn => {
                    btn.addEventListener('click', async (e) => {
                        const id = e.target.dataset.id;
                        const filename = e.target.dataset.filename;
                        
                        if (confirm('确定要删除这张图片吗？')) {
                            try {
                                const response = await fetch(`/delete?id=${id}&filename=${filename}`, {
                                    method: 'DELETE'
                                });
                                
                                const result = await response.json();
                                
                                if (result.success) {
                                    showMessage('删除成功', 'success');
                                    loadImageList(); // 重新加载列表
                                } else {
                                    showMessage('删除失败: ' + result.message, 'error');
                                }
                            } catch (error) {
                                showMessage('删除失败: ' + error.message, 'error');
                            }
                        }
                    });
                });
                
            } catch (error) {
                showMessage('加载图片列表失败: ' + error.message, 'error');
            }
        }
        
        // 显示消息
        function showMessage(text, type) {
            statusMessage.textContent = text;
            statusMessage.className = 'status-message';
            if (type) {
                statusMessage.classList.add(type);
            }
        }
        
        // 页面加载时加载图片列表
        window.addEventListener('load', loadImageList);
    </script>
</body>
</html>
